<template>
  <div>
    <el-drawer v-model="_isOpen" size="1140" title="选择定额模板" :direction="'rtl'" modal-class="quota-drawer">
      <template #header>
        <h4>选择定额模板</h4>
      </template>
      <template #default>
        <el-container class="out-container">
          <el-aside width="220px">
            <template v-if="treeData.length > 0">
              <p class="pl10 pt24 pb20"><img src="@/assets/images/file-icon.png" alt="" class="mr16" />定额工程类型</p>
              <el-tree
                :default-expand-all="false"
                :data="treeData"
                :props="{
                  children: 'childFolder',
                  label: 'folderName'
                }"
                highlight-current
                @node-click="handleNodeClick"
              >
                <template #default="{ node, data }">
                  <span class="tree-node">
                    <img src="@/assets/images/file-icon.png" alt="" />
                    <span class="text-over" :title="node.label || '-'">{{ node.label }}</span>
                  </span>
                </template>
              </el-tree>
            </template>

            <div v-else style="display: flex; justify-content: center; width: 100%">
              <el-empty description="暂无数据" />
            </div>
          </el-aside>
          <el-main>
            <el-container class="inner-container">
              <el-aside width="200px">
                <header class="sticky-block">
                  <el-input
                    v-model="searchkey"
                    clearable
                    style="width: 160px"
                    placeholder="请输入工程名称"
                    :prefix-icon="Search"
                    :disabled="JSON.stringify(currTreeNode) === '{}'"
                    @change="getProjectFun"
                  />
                </header>
                <div class="temp-list">
                  <p class="title">{{ currTreeNode.folderName || "-" }}</p>
                  <div
                    class="temp-item"
                    :class="{ active: currQuota.projectId === item.projectId }"
                    v-for="(item, index) of quotaList"
                    :key="index"
                    @click="changeQuota(item)"
                  >
                    <p class="text-over" :title="item.projectName || '-'">{{ item.projectName || "-" }}</p>
                  </div>
                </div>
              </el-aside>
              <el-main>
                <el-table
                  ref="tableRef"
                  class="jzt-table"
                  :data="tableData"
                  stripe
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                >
                  <template #empty>
                    <el-empty description="这里暂时什么都没有" />
                  </template>
                  <el-table-column type="selection" width="55" />
                  <el-table-column label="序号" fixed type="index" width="60" />
                  <el-table-column prop="quotaName" show-overflow-tooltip label="定额名称" width="200">
                    <template #default="scope">
                      {{ scope.row.quotaName || "-" }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="standardDesc" show-overflow-tooltip label="材料及工艺说明" width="200">
                    <template #default="scope">
                      <el-button type="primary" class="underline" link @click="openMaterialDialog(scope.row)">
                        <p class="text-over" style="max-width: 180px">{{ scope.row.standardDesc || "-" }}</p>
                      </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column prop="unit" show-overflow-tooltip label="单位" width="135">
                    <template #default="scope">
                      {{ useCodeArrStore().getDictName("shop_unit", scope.row.unit) }}
                      <!-- <p>{{ scope.row.unit }}</p> -->
                    </template>
                  </el-table-column>
                  <el-table-column prop="lostRate" show-overflow-tooltip label="耗损率" width="135">
                    <template #default="scope"> {{ scope.row.lostRate || "-" }}%</template>
                  </el-table-column>
                  <el-table-column label="报价">
                    <el-table-column prop="mainQuoteMoney" label="定额主材" width="120">
                      <template #default="scope">
                        <!-- <p>{{ scope.row.mainQuoteMoney || "-" }}</p> -->
                        <el-button class="underline" type="primary" link @click="openCailiaoDialog(scope.row, 1)">
                          ¥{{ scope.row.mainQuoteMoney || "-" }}
                        </el-button>
                      </template>
                    </el-table-column>
                    <el-table-column prop="auxiliaryQuoteMoney" label="定额辅材" width="120">
                      <template #default="scope">
                        <!-- <p>{{ scope.row.auxiliaryQuoteMoney || "-" }}</p> -->
                        <el-button class="underline" type="primary" link @click="openCailiaoDialog(scope.row, 2)">
                          ¥{{ scope.row.auxiliaryQuoteMoney || "-" }}
                        </el-button>
                      </template>
                    </el-table-column>
                    <el-table-column prop="workerQuoteMoney" label="人工" width="120">
                      <template #default="scope">
                        <el-button class="underline" type="primary" link @click="openArtificialDialog(scope.row)">
                          ¥{{ scope.row.workerQuoteMoney || "-" }}
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table-column>
                  <el-table-column prop="quoteTotalMoney" label="报价合计" width="120">
                    <template #default="scope"> ¥{{ scope.row.quoteTotalMoney || "-" }} </template>
                  </el-table-column>
                </el-table>
              </el-main>
            </el-container>
          </el-main>
        </el-container>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="info" @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick" :disabled="selectedList.length <= 0">
            已选中({{ selectedList.length }})
          </el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 材料工艺详情抽屉 -->
    <materialDrawer v-model:isOpen="materialIsOpen" :optionInfo="optionInfoMaterial" />

    <!-- 固定商品-主材辅材明细列表弹窗 -->
    <cailiaoDetailList v-model:isOpen="cailiaoIsOpen" :optionInfo="optionInfoCailiao" />

    <!-- 组合条件-主材辅材明细列表弹窗 -->
    <cailiaoDetailListZuHe v-model:isOpen="cailiaoIsOpenZuHe" :optionInfo="optionInfoCailiaoZuHe" />

    <!-- 人工明细列表弹窗 -->
    <artificialDetailList v-model:isOpen="artificialIsOpen" :optionInfo="optionInfoArtificial" />
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { Search } from "@element-plus/icons-vue";
import materialDrawer from "./materialDetail.vue";
import {
  getfolderTree,
  getProject,
  getQuotaList,
  getQuotaList2,
  inventoryAddQuota,
  packageAddQuota,
  packageMainMaterial,
  getAuxiliaryProductsByContentId,
  getMainProductsByContentId,
  quotaProductList,
  quotaWorkerList,
  quotaProductConditionList
} from "@/apis/quote-price/following";
import useCodeArrStore from "@/store/modules/select";
import cailiaoDetailList from "./cailiaoDetailList.vue"; //主材、辅材明细---固定商品
import cailiaoDetailListZuHe from "./cailiaoDetailListZuHe.vue"; //主材、辅材明细---条件组合
import artificialDetailList from "./artificialDetailList.vue"; //人工明细

const emit = defineEmits(["update:isOpen", "submitOk"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  optionInfo: {
    type: Object,
    default: () => {
      return {
        type: 1, //1-常规 2-套餐
        spaceId: "",
        budgetId: ""
      };
    }
  },
  doSubmit: { type: Boolean, default: true }
});
const tableRef = ref();
const treeData = ref([]); //定额工程类型tree
const currTreeNode = ref({}); //选中的工程类型树节点
const quotaList = ref([]); //定额列表
const currQuota = ref({ projectId: -1 }); //当前选中的定额obj
const searchkey = ref("");
const tableData = ref([]); //定额模板下的商品sku列表
const selectedList = ref([]);
const materialIsOpen = ref(false);
const optionInfoMaterial = ref({ type: "view", detail: {} });
const cailiaoIsOpen = ref(false); //固定商品-主材辅材明细列表弹窗
const optionInfoCailiao = ref({ type: "zhu", detail: {} });
const cailiaoIsOpenZuHe = ref(false); //组合条件-主材辅材明细列表弹窗
const optionInfoCailiaoZuHe = ref({ type: "zhu", detail: {} });
const artificialIsOpen = ref(false); //人工明细列表弹窗
const optionInfoArtificial = ref({ detail: {} });

//   watch(
//     () => props.filterData,
//     val => {
//       console.log("传递过来的属性数据", val);
//       _filterData.value = JSON.parse(JSON.stringify(val));
//       _filterDataCopy.value = JSON.parse(JSON.stringify(val));
//     },
//     { deep: true, immediate: true }
//   );
const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

onMounted(() => {
  getfolderTreeFun();
});

//打开材料明细 type 1-主材 2-辅材材
const openCailiaoDialog = (item, type = 1) => {
  console.log(99999, item);
  if (item.mainProductShowType === 2 || item.auxiliaryProductShowType === 2) {
    //条件组合
    cailiaoIsOpenZuHe.value = true;
  } else {
    //固定商品
    cailiaoIsOpen.value = true;
  }
  getProductsByContentIdFun(item, type);
};

//查询主材、辅材明细列表 type 1-主材 2-辅材材
const getProductsByContentIdFun = async (item, type = 1, code) => {
  if (item.mainProductShowType === 2 || item.auxiliaryProductShowType === 2) {
    //主材mainProductShowType 辅材auxiliaryProductShowType :1-具体商品 2-条件组合

    console.log("条件组合");

    quotaProductConditionList({ quotaId: item.quotaId, productType: type }).then(res => {
      if (res.code === 200) {
        optionInfoCailiaoZuHe.value.actionType = "view";
        optionInfoCailiaoZuHe.value.type = type === 1 ? "zhu" : "fu";
        optionInfoCailiaoZuHe.value.project = { ...item };
        optionInfoCailiaoZuHe.value.detail = { ...res.data, contentId: item.contentId, _time: new Date().getTime() };
        optionInfoCailiaoZuHe.value.getDetailList = getProductsByContentIdFun;
      }
    });

    // await packageMainMaterial({
    //   productType: type, //1-主材 2-辅材材
    //   budgetId: props.optionInfo.budgetId,
    //   contentId: item.contentId,
    //   code
    // }).then(res => {
    //   if (res.code === 200) {
    //     optionInfoCailiao.value.actionType = "view";
    //     optionInfoCailiao.value.type = type === 1 ? "zhu" : "fu";
    //     optionInfoCailiao.value.project = { ...item };
    //     optionInfoCailiao.value.detail = { ...res.data, contentId: item.contentId, _time: new Date().getTime() };
    //     optionInfoCailiao.value.getDetailList = getProductsByContentIdFun;
    //   }
    // });
  } else {
    //非条件组合
    console.log("固定商品", item);

    quotaProductList({ quotaId: item.quotaId, productType: type }).then(res => {
      if (res.code === 200) {
        optionInfoCailiao.value.dialogType = "de"; //ys-预算报价  de-定额模板
        optionInfoCailiao.value.actionType = "view";
        optionInfoCailiao.value.type = type === 1 ? "zhu" : "fu";
        optionInfoCailiao.value.project = { ...item };
        optionInfoCailiao.value.detail = { ...res.data, contentId: item.contentId, _time: new Date().getTime() };
        optionInfoCailiao.value.getDetailList = getProductsByContentIdFun;
      }
    });

    // if (type === 1) {
    //   //主材明细
    //   await getMainProductsByContentId({ contentId: item.contentId }).then(res => {
    //     if (res.code === 200) {
    //       console.log("主材明细", res.data);
    //       optionInfoCailiao.value.actionType = "view";
    //       optionInfoCailiao.value.type = "zhu";
    //       optionInfoCailiao.value.project = { ...item };
    //       optionInfoCailiao.value.detail = { ...res.data, contentId: item.contentId, _time: new Date().getTime() };
    //       optionInfoCailiao.value.getDetailList = getProductsByContentIdFun;
    //     }
    //   });
    // } else {
    //   //辅材明细
    //   await getAuxiliaryProductsByContentId({ contentId: item.contentId }).then(res => {
    //     if (res.code === 200) {
    //       console.log("辅材明细", res.data);
    //       optionInfoCailiao.value.actionType = "view";
    //       optionInfoCailiao.value.type = "fu";
    //       optionInfoCailiao.value.project = { ...item };
    //       optionInfoCailiao.value.detail = { ...res.data, contentId: item.contentId, _time: new Date().getTime() };
    //       optionInfoCailiao.value.getDetailList = getProductsByContentIdFun;
    //     }
    //   });
    // }
  }
};

//打开人工明细
const openArtificialDialog = item => {
  artificialIsOpen.value = true;
  getWorkerListByContentIdFun(item);
};
//查询人工明细列表
const getWorkerListByContentIdFun = item => {
  quotaWorkerList({ quotaId: item.quotaId }).then(res => {
    if (res.code === 200) {
      console.log("人工明细", res.data);
      optionInfoArtificial.value.dialogType = "de"; //ys-预算报价  de-定额模板
      optionInfoArtificial.value.actionType = "view";
      optionInfoArtificial.value.detail = { ...res.data, _time: new Date().getTime() };
    }
  });
};

//打开工艺材料说明
const openMaterialDialog = item => {
  materialIsOpen.value = true;
  optionInfoMaterial.value.type = "view";
  optionInfoMaterial.value.detail = { ...item, _time: new Date().getTime() };
};

/**查询定额工程文件夹tree */
const getfolderTreeFun = () => {
  getfolderTree().then(res => {
    if (res.code === 200) {
      treeData.value = res.data;
    }
  });
};

/**切换tree node定额工程类型 */
const handleNodeClick = node => {
  if (node.childFolder.length > 0) return;
  currTreeNode.value = node;
  getProjectFun();
};
/**查询工程类型 */
const getProjectFun = () => {
  getProject({ folderId: currTreeNode.value.folderId, projectName: searchkey.value }).then(res => {
    if (res.code === 200) {
      quotaList.value = res.data || [];
    }
  });
};

/**切换工程类型，查询table列表数据 */
const changeQuota = item => {
  currQuota.value = item;
  getQuotaList2({ projectId: item.projectId, budgetId: props.optionInfo.budgetId }).then(res => {
    if (res.code === 200) {
      tableData.value = res.data;
    }
  });
};

const handleSelectionChange = list => {
  selectedList.value = list;
  // console.log("选中的row===", selectedList.value);
};

const reset = () => {
  selectedList.value = [];
  tableRef.value.clearSelection();
  searchkey.value = "";
  currTreeNode.value?.folderId && getProjectFun();
};

const cancelClick = () => {
  reset();
  _isOpen.value = false;
  // emit("changeAttr");
};
const confirmClick = () => {
  if (props.doSubmit) {
    if (props.optionInfo.type === 1) {
      //常规
      inventoryAddQuota({
        spaceId: props.optionInfo.spaceId,
        budgetId: props.optionInfo.budgetId,
        quotaIds: selectedList.value.map(item => item.quotaId)
      }).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: "定额导入成功",
            type: "success"
          });
          reset();
          emit("submitOk");
          _isOpen.value = false;
        }
      });
    } else if (props.optionInfo.type === 2) {
      //套餐
      packageAddQuota({
        spaceId: props.optionInfo.spaceId,
        budgetId: props.optionInfo.budgetId,
        quotaIds: selectedList.value.map(item => item.quotaId)
      }).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: "定额导入成功",
            type: "success"
          });
          reset();
          emit("submitOk");
          _isOpen.value = false;
        }
      });
    }
  } else {
    emit(
      "customSubmit",
      selectedList.value.map(item => item.quotaId)
    );
  }

  // emit("changeAttr");
};

defineExpose({});
</script>

<style lang="scss">
.quota-drawer {
  .el-drawer {
    box-shadow: -8px 0px 16px 0px rgba(0, 38, 73, 0.1);
    border-radius: 10px 0px 0px 10px;
  }
  .el-drawer__header {
    font-size: 18px;
    color: #131414;
    padding-bottom: 20px !important;
    margin-bottom: 0 !important;
    border-bottom: 1px solid #dcdfe6;
    h4 {
      font-weight: normal;
      position: relative;
      padding-left: 14px;
    }
  }
  .el-drawer__body {
    padding: 0 !important;
  }
  .el-drawer__footer {
    display: flex;
    justify-content: flex-end;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    padding: 14px 20px;
    .el-button--primary {
      --el-button-bg-color: #424e66;
      border: none;
    }
    .el-button.el-button--info {
      --el-color-info: #f2f3f5;
      --el-color-white: #1d2129;
      &:hover {
        --el-button-hover-bg-color: #f2f3f5 !important;
        border-color: #f2f3f5 !important;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.el-button--primary.is-link.underline {
  border-radius: 0;
  border-bottom: 1px solid #213270;
}
:deep(.el-tree) {
  width: 100%;
  overflow-x: auto;
  padding-bottom: 94px;

  .el-icon.el-tree-node__expand-icon {
    padding-left: 10px;
  }
  .el-tree-node__content {
    line-height: 32px;
    height: 32px;
    .tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      img {
        margin-right: 10px;
      }
      & > span {
        flex: 1;
        max-width: 135px;
      }
    }
  }
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #eef1f4 !important;
    color: #1a1a1a;
    tree-node i {
      color: #1a1a1a !important;
    }
  }
}

:deep(.inner-container) {
  .sticky-block {
    text-align: center;
    padding: 20px 0;
  }
  .temp-list {
    .temp-item {
      line-height: 32px;
      height: 32px;
      padding: 0 20px;
      cursor: pointer;
      color: #86909c;
      &.active {
        background-color: #eef1f4;
        color: #3d3d3d;
      }
    }
  }
  .el-aside {
    p.title {
      padding-top: 0 !important;
      padding-bottom: 0 !important;
      margin-bottom: 10px;
    }
  }
}
</style>
